(:
  A procedure to select the contents of the "chat" interventions
:)
declare boundary-space strip;
import module namespace
    jj = "http://kumquat.emse.fr/utilitaires"
    at "jjutils.xq" ;

declare function local:get-time-milli ($item as element()) as xs:integer 
		{
			xs:integer($item/info[@name="time"]/time/date)
		};

<display>{
let $maxdelta := if ($arguments[2]) then xs:integer($arguments[2]) * 1000 else 60000
let $t := $arguments[1]
let $d := doc($t)/display/item
let $myitems := 
	for $e at $p in $d
	let $prev := $e/preceding-sibling::item[1]
	let $succ := $e/following-sibling::item[1]
	let $now := local:get-time-milli($e)
	let $prevtime := if (fn:empty($prev)) then 
		0 else 
		local:get-time-milli($prev)
	let $succtime := if (fn:empty($succ))
		then $now + 2 * $maxdelta
		else local:get-time-milli($succ)
	where   $now - $prevtime gt $maxdelta or
			$succtime - $now gt $maxdelta	
	return 
	<item>{
		<info name="type">{
			if (($now - $prevtime) gt $maxdelta)
	 		then "textboard-begin-write"
	 		else "textboard-end-write"
	    }</info>,
		for $info in $e/info[@name!=("type")]
		return $info
	}</item>
for $e at $p in $myitems where $e/info[@name="type"]="textboard-begin-write"
return
let $end := $myitems[$p+1]
let $next := $myitems[$p+2]
let $duration := if (fn:empty($end) or $end/info[@name="type"]="textboard-begin-write")
	then 0
	else local:get-time-milli($end) - local:get-time-milli($e)
let $pause := if ($end and $end/info[@name="type"]="textboard-begin-write")
		then (local:get-time-milli($end) - local:get-time-milli($e))
 		else if ($next)
			then (local:get-time-milli($next) - local:get-time-milli($end))
			else ()
return
<item>{
    <info name="type">textboard-block</info>,
    <info name="time"><time>{
	<date>{local:get-time-milli($e)}</date>,
	<duration>{$duration}</duration>
    }</time></info>,
    $e/info[@name="src-anchor"],
    $e/info[@name="user"],
    $e/info[@name="currenttext"],
    $e/info[@name="room"],
    <info name="content">{
	<text color="blue">{
		fn:concat("block, duration: ",
			jj:formatMMMSS($duration), 
			" until next ",
			$maxdelta idiv 1000,
			"s break. ",
			if ($pause)
				then fn:concat("Following pause: ",jj:formatMMMSS($pause),"s")
				else ()
		)
	}</text>
    }</info>
}</item>
}</display>
